package com.example.demo.designpattern.strategy.context;

import java.util.EnumMap;
import java.util.Map;

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import com.example.demo.designpattern.strategy.annotation.TestMethodStrategy;
import com.example.demo.designpattern.strategy.enums.TestMethod;
import com.example.demo.designpattern.strategy.service.TestMethodService;

@Component
public class TestMethodContext implements ApplicationListener<ContextRefreshedEvent> {

    private static final Map<TestMethod, TestMethodService> handlerMap = new EnumMap<TestMethod, TestMethodService>(TestMethod.class);

    public static TestMethodService getHandler(TestMethod testMethod) {
        return handlerMap.get(testMethod);
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        Map<String, Object> beans = contextRefreshedEvent.getApplicationContext().getBeansWithAnnotation(TestMethodStrategy.class);
        beans.forEach((key, bean) -> {
            //根据注解获取类
            TestMethodStrategy strategy = bean.getClass().getAnnotation(TestMethodStrategy.class);
            TestMethod httpMethod = strategy.value();
            handlerMap.put(httpMethod, (TestMethodService) bean);
        });
    }
}
